﻿using System;
using System.Linq;
using TweetSharp.Twitter.Extensions;
using TweetSharp.Twitter.Fluent;
using TweetSharp.Twitter.Model;

namespace Halfwit.Pollers
{
    public class UserPoller : TwitterPoller
    {
        public UserPoller(Func<String> getUsername, Action<TwitterPoller, TwitterResult> callback)
            : base(callback)
        {
            _getUsername = getUsername;
            Description = "User Timeline";
        }

        private Func<String> _getUsername;
        private string _lastUsername;

        protected override bool CanPoll()
        {
            var username = _getUsername();
            if (username == null) return false;
            return username.Any(c => !Char.IsLetterOrDigit(c) || c != '_');
        }

        protected override ITwitterLeafNode CreateRequest(IFluentTwitter twitter)
        {
            var username = _getUsername();

            // search anew if the username has changed since last time
            if (username != _lastUsername) Reset();

            _lastUsername = username;

            var request = twitter.Statuses().OnUserTimeline().For(username);
            if (LastId.HasValue)
            {
                request = request.Since(LastId.Value);
            }
            else
            {
                request = request.Take(Properties.Settings.Default.MaxTweets);
            }
            return request;
        }

        protected override void OnSuccessfulRequest(TwitterResult result)
        {
            Description = "Tweets by " + _lastUsername;

            var tweets = result.AsStatuses();
            if (tweets == null || tweets.Count() == 0) return;

            LastId = tweets.Max(t => t.Id);
        }
    }
}
